import { ref, watch } from 'vue'
import { useRoute } from 'vue-router'

export const useSEO = () => {
  const route = useRoute()
  const title = ref('')
  const description = ref('')
  const keywords = ref('')
  const ogImage = ref('')

  const updateMeta = ({ title: newTitle, description: newDescription, keywords: newKeywords, image: newImage }) => {
    if (newTitle) {
      title.value = newTitle
      document.title = `${newTitle} - 公司名称`
      updateMetaTag('og:title', newTitle)
    }

    if (newDescription) {
      description.value = newDescription
      updateMetaTag('description', newDescription)
      updateMetaTag('og:description', newDescription)
    }

    if (newKeywords) {
      keywords.value = newKeywords
      updateMetaTag('keywords', newKeywords)
    }

    if (newImage) {
      ogImage.value = newImage
      updateMetaTag('og:image', newImage)
    }

    // 添加其他 Open Graph 标签
    updateMetaTag('og:type', 'website')
    updateMetaTag('og:url', window.location.href)
  }

  const updateMetaTag = (name, content) => {
    let meta = document.querySelector(`meta[${name.startsWith('og:') ? 'property' : 'name'}="${name}"]`)
    if (!meta) {
      meta = document.createElement('meta')
      meta.setAttribute(name.startsWith('og:') ? 'property' : 'name', name)
      document.head.appendChild(meta)
    }
    meta.setAttribute('content', content)
  }

  // 添加结构化数据
  const addStructuredData = (data) => {
    let script = document.querySelector('#structured-data')
    if (!script) {
      script = document.createElement('script')
      script.id = 'structured-data'
      script.type = 'application/ld+json'
      document.head.appendChild(script)
    }
    script.textContent = JSON.stringify(data)
  }

  // 监听路由变化
  watch(() => route.path, () => {
    // 清除旧的结构化数据
    const oldScript = document.querySelector('#structured-data')
    if (oldScript) {
      oldScript.remove()
    }
  })

  return {
    updateMeta,
    addStructuredData
  }
}
